const express = require('express')
const router = express.Router()

const Admin = require('../Model/Admin')
const History = require('../Model/History')
const getter = require('../middleware/AutoToken').getter
// login
router.post('/login', (req, res, next) => {
  const user = req.body
  console.log(req.get('token'))
  if (user && user.username && user.password) {
    Admin.findOne({ username: user.username })
      .exec((err, doc) => {
        if (err) {
          res.hasError(500, '系统错误', err)
        } else if (!doc) {
          res.hasError(404, '用户不存在')
        } else if (doc.password !== res.solt(user.password)) {
          res.hasError(404, '密码错误')
        } else if (doc.state !== 200) {
          res.hasError(404, `用户已经被${doc.state === 404 ? '删除' : '禁用'}`)
        } else {
          doc.password = ''
          History.create({
            username: doc.username,
            user: doc._id,
            path: '/login',
            desc: user.desc
          }, (err, doc) => {
          })
          let token = {}
          Object.assign(token, { user: doc })
          Object.assign(token, { expire: Date.now() + 60 * 60 * 1000 })
          Object.assign(token, { token: getter(token) })
          res.success(token)
        }
      })
  } else {
    res.hasError(404, '缺少用户名或者密码')
  }
})

// loginout
  .get('/login_log', (req, res, next) => {
    const username = req.query.username
    console.log(username)
    if (username) {
      History.findOne({ username: username, path: '/login' })
        .sort({ _id: -1 })
        .exec((err, doc) => {
          if (err || !doc) {
            res.success('没有登录历史')
          } else {
            console.log('hist', doc)
            res.success(`${doc.username}, 上次登录: ${res.dateformat(doc.createdAt)}`)
          }
        })
    } else {
      res.success('没有登录历史')
    }
  })

module.exports = router